package cn.kgc.springboot.vue.service.impl;

import cn.kgc.springboot.vue.commons.QueryCondition;
import cn.kgc.springboot.vue.entity.Permission;
import cn.kgc.springboot.vue.entity.Role;
import cn.kgc.springboot.vue.entity.RolePermission;
import cn.kgc.springboot.vue.entity.UserRole;
import cn.kgc.springboot.vue.mapper.PermissionMapper;
import cn.kgc.springboot.vue.mapper.RoleMapper;
import cn.kgc.springboot.vue.mapper.RolePermissionMapper;
import cn.kgc.springboot.vue.mapper.UserRoleMapper;
import cn.kgc.springboot.vue.response.ResponseResult;
import cn.kgc.springboot.vue.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author mengshun
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2024-12-21 09:50:50
*/
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService{

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public ResponseResult rolePage(QueryCondition<Role> queryCondition) {

        Page<Role> rolePage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());
        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
        Role searchParams = queryCondition.getSearchParams();
        String roleCh = searchParams.getRoleCh();
        String roleEn = searchParams.getRoleEn();
        lambda.like(StringUtils.isNotBlank(roleEn),Role::getRoleEn,roleEn)
                .like(StringUtils.isNotBlank(roleCh),Role::getRoleCh,roleCh)
                .orderByDesc(Role::getCreateTime);

        baseMapper.selectPage(rolePage,lambda);


        return ResponseResult.success()
                .data("total",rolePage.getTotal())
                .data("tableData",rolePage.getRecords());
    }

    @Override
    public ResponseResult deleteRole(Integer id) {

        // 1. 删除的角色是否被占用

        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getRoleId,id);

        List<UserRole> userRoles = userRoleMapper.selectList(lambda);
        if (ObjectUtils.isNotNull(userRoles)){
            return  ResponseResult.fail().message("角色被占用");
        }

        //2. 删除角色信息
        baseMapper.deleteById(id);

        // 3.删除角色对应的权限
        LambdaQueryWrapper<RolePermission> lambda1 = new QueryWrapper<RolePermission>().lambda();
        lambda1.eq(RolePermission::getRoleId,id);
        rolePermissionMapper.delete(lambda1);

        return ResponseResult.success();
    }

    @Override
    public ResponseResult rolePermissions(Integer id) {

        // 根据角色id  查询角色权限id  role_permission
        LambdaQueryWrapper<RolePermission> lambda = new QueryWrapper<RolePermission>().lambda();
        lambda.eq(RolePermission::getRoleId,id);

        Set<Integer> pIds = rolePermissionMapper.selectList(lambda)
                .stream().map(rp -> rp.getPerId())
                .collect(Collectors.toSet());

        if (ObjectUtils.isNull(pIds)){
            return ResponseResult.success()
                    .data("isMenuIds",new ArrayList<>());
        }

        LambdaQueryWrapper<Permission> lambda1 = new QueryWrapper<Permission>().lambda();
        lambda1.in(Permission::getId,pIds)
                .eq(Permission::getIsMenu,2);

        List<Integer> isMenuIds = permissionMapper.selectList(lambda1)
                .stream().map(permission -> permission.getId())
                .collect(Collectors.toList());

        return ResponseResult.success()
                .data("isMenuIds",isMenuIds);
    }

    @Override
    public ResponseResult addRolePermissions(HashMap<String, Object> params) {

        List<Integer> pIds  = (List<Integer>) params.get("newKeys");
        Integer rid = (Integer) params.get("rid");

        // 根据角色id  删除角色又有的权限信息
        LambdaQueryWrapper<RolePermission> lambda = new QueryWrapper<RolePermission>().lambda();
        lambda.eq(RolePermission::getRoleId,rid);
        rolePermissionMapper.delete(lambda);

        // 添加角色新权限

        pIds.forEach(pid->{
            RolePermission rolePermission = new RolePermission(rid, pid);
            rolePermissionMapper.insert(rolePermission);
        });

        return ResponseResult.success();
    }
}




